package com.example.web_playback

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class LoadingActivity : AppCompatActivity() {
    
    private lateinit var progressBar: ProgressBar
    private lateinit var progressText: TextView
    private lateinit var statusText: TextView
    private lateinit var retryButton: Button
    
    private lateinit var downloadManager: ResourceDownloadManager
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置全屏模式
        setupFullscreen()
        
        setContentView(R.layout.loading_activity)
        
        initializeViews()
        setupDownloadManager()
        startDownload()
    }
    
    private fun setupFullscreen() {
        // 隐藏状态栏和导航栏
        window.decorView.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_FULLSCREEN
            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        )
        
        // 设置窗口标志
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        
        // 隐藏ActionBar
        supportActionBar?.hide()
    }
    
    private fun initializeViews() {
        progressBar = findViewById(R.id.progressBar)
        progressText = findViewById(R.id.progressText)
        statusText = findViewById(R.id.statusText)
        retryButton = findViewById(R.id.retryButton)
        
        retryButton.setOnClickListener {
            retryDownload()
        }
    }
    
    private fun setupDownloadManager() {
        downloadManager = ResourceDownloadManager(this)
    }
    
    private fun startDownload() {
        Log.d("LoadingActivity", "开始下载流程")
        statusText.text = "正在检查资源..."
        
        // 检查是否需要下载
        if (isAllResourcesDownloaded()) {
            Log.d("LoadingActivity", "所有资源已下载，直接进入主界面")
            // 所有资源已下载，直接进入主界面
            enterMainActivity()
            return
        }
        
        val totalDirectories = downloadManager.resourceDirectories.size
        Log.d("LoadingActivity", "需要下载 $totalDirectories 个资源目录")
        
        statusText.text = "开始下载资源..."
        progressBar.max = totalDirectories
        
        downloadManager.downloadAllResources(object : ResourceDownloadManager.DownloadCallback {
            override fun onProgress(progress: Int, total: Int) {
                runOnUiThread {
                    progressBar.progress = progress
                    progressText.text = "$progress / $total"
                    statusText.text = "正在下载资源... ($progress/$total)"
                    Log.d("LoadingActivity", "下载进度: $progress/$total")
                }
            }
            
            override fun onComplete() {
                runOnUiThread {
                    statusText.text = "下载完成！"
                    progressText.text = "完成"
                    Log.d("LoadingActivity", "所有资源下载完成")
                    // 延迟1秒后进入主界面
                    android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                        enterMainActivity()
                    }, 1000)
                }
            }
            
            override fun onError(error: String) {
                runOnUiThread {
                    statusText.text = "下载失败: $error"
                    retryButton.visibility = View.VISIBLE
                    Log.e("LoadingActivity", "资源下载失败: $error")
                }
            }
        })
    }
    
    private fun retryDownload() {
        retryButton.visibility = View.GONE
        progressBar.progress = 0
        progressText.text = "0 / 0"
        startDownload()
    }
    
    private fun isAllResourcesDownloaded(): Boolean {
        val downloadedCount = downloadManager.getDownloadedResources().size
        val totalCount = downloadManager.resourceDirectories.size
        Log.d("LoadingActivity", "资源检查: 已下载=$downloadedCount, 总计=$totalCount")
        return downloadedCount == totalCount
    }
    
    private fun enterMainActivity() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        downloadManager.destroy()
    }
}
